package com.csdn.exer;

import java.util.HashMap;
import java.util.Map;

public class RedisTokenDao implements TokenDao {

    private long expireIn = 2 * 3600 * 1000L;

    @Override
    public Token buildOrQuerry(String key, Map<String, String> values) {
        Token token;
        Map<String, String> tokenMap = RedisUtil.getInstance().hgetAll(key);

        if (tokenMap == null || tokenMap.size() == 0) {
            token = Token.createToken(expireIn);
            tokenMap = new HashMap<>();
            tokenMap.put("generateTime", String.valueOf(token.getGenerateTime()));
            tokenMap.put("expireTime", String.valueOf(token.getExpireTime()));
            tokenMap.put("expireIn", String.valueOf(token.getExpireIn()));
            tokenMap.put("accessToken", String.valueOf(token.getAccessToken()));
            RedisUtil.getInstance().hmset(key, tokenMap);
            RedisUtil.getInstance().expire(key, (int) expireIn);
            RedisUtil.getInstance().hmset(getTokenKey(token.getAccessToken()), values);
            RedisUtil.getInstance().expire(getTokenKey(token.getAccessToken()), (int) expireIn);
        }
//        else {
            // todo 获取json的解析包
//            token = JSONObject.parseObject(JSONObject.toString(tokenMap), Token.class);
//        }

//        return token;
        return null;
    }

    @Override
    public Map<String, String> tokenQuery(String token) {
        return (Map<String, String>) RedisUtil.getInstance().hgetAll(getTokenKey(token));
    }

    private String getTokenKey(String token) {
        return "token:" + token;
    }
}
